import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { ControlApiService } from '@core/controlApi.service';
import { DatePipe } from '@angular/common';
import { DomSanitizer } from '@angular/platform-browser';
import { StationDevtypeService } from '@core/stationDevtype.service';
import { JzjcMainService } from '../jzjc/jzjc_main/jzjc_main.service';
import { _HttpClient } from '@delon/theme';
import { TreeTools } from '@core/treeTools.tool';
import { environment } from '../../../../environments/environment';
declare const echarts: any;

@Component({
    selector: 'app-diagnose',
    templateUrl: './diagnose.component.html',
    styleUrls: ['./diagnose.component.less']
})

export class ControlDiagnoseComponent implements OnInit {
    themeClass = 'whitetheme';
    treeNodeStyle = { 'max-width': '300px', 'max-height': '400px', 'overflow-y': 'auto', 'overflow-x': 'hidden' };
    selectClass = 'defaultSelect';
    queryParams: any = {};
    testType = '';
    dqtxshow = {};
    dcshow = {};

    czjyAlarmType = '';
    dataSet: any = [];
    sjValue: any;

    stepNameSelect: any = [];

    wtkIframe: any;

    battleTimeValue: any;
    zctiframe: any;
    battleStationId = '';
    battleStationSelect: any = [];

    eleStartValue: any;
    eleEndValue: any;

    devStartValue: any;
    devEndValue: any;

    beforeValue = 15;
    afterValue = 10;

    wzjyData: any = [{ id: '' }];
    electricalnml = false;
    scValue = 10;

    constructor(
        private activatedRoute: ActivatedRoute,
        private controlApiService: ControlApiService,
        private msg: NzMessageService,
        private http: _HttpClient,
        private sanitizer: DomSanitizer,
        private datePipe: DatePipe,
        private statdevtype: StationDevtypeService,
        private router: Router,
        public treeTools: TreeTools,
        private jzjcMainService: JzjcMainService
    ) { }

    ngOnInit() {
        this.activatedRoute.queryParams.subscribe((params: any) => {
            if (JSON.stringify(params) != '{}') {
                Object.assign(this.queryParams, params);
                this.queryParams.DEVTYPE = this.formatEmpty(decodeURI(decodeURI(params.DEVTYPE)));
                this.queryParams.STATIONNAME = this.formatEmpty(decodeURI(decodeURI(params.STATIONNAME)));
                this.queryParams.ALARMTEXT = this.formatEmpty(decodeURI(decodeURI(params.ALARMTEXT)));
                this.queryParams.DEVNAME = this.formatEmpty(decodeURI(decodeURI(params.DEVNAME)));
                this.battleTimeValue = this.formatEmpty(this.queryParams.TIME);
                this.battleStationId = this.formatEmpty(this.queryParams.STATIONID);
                // 电气特性时间
                this.tqtxTime('first', this.queryParams);
                this.electricalnml = true;
                this.czjyAlarmType = this.queryParams.ALARMTYPE;
                this.devStartValue = this.datePipe.transform(new Date().getTime() - 2592000000, 'yyyy-MM-dd');
                this.devEndValue = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
                // 车站
                this.statdevtype.getStation((resdata) => {
                    // 站场回放
                    this.battleStationSelect = this.treeTools.formatTreeNode(resdata);
                    this.battleSearch();
                });
                // 设备趋势
                this.healthSearch();
                // 处置流程
                this.controlApiService.menuProcess().subscribe((res: any) => {
                    for (const item of res) {
                        this.stepNameSelect.push({ id: item.cid, name: item.content });
                    }
                });
            }
        });
    }

    formatEmpty(data) {
        switch (data) {
            case undefined: case 'undefined': case null: case 'null':
                return '';
            default:
                return data;
        }
    }
    // 电气特性时间
    tqtxTime(type, params) {
        let stime: any;
        switch (type) {
            case 'first':
                stime = params.TIME;
                break;
            default:
                stime = this.datePipe.transform(this.eleStartValue, 'yyyy-MM-dd HH:mm:ss');
                break;
        }
        // 报警时间往前推间隔一半
        this.eleStartValue = this.datePipe.transform(new Date(stime).getTime() - (this.scValue * 60000 / 2), 'yyyy-MM-dd HH:mm:ss');
        this.sjValue = this.eleStartValue;
        // 当前时间未超过报警时间，则取当前时间；反之向后取间隔一半
        switch (true) {
            case (new Date().getTime() - new Date(stime).getTime() < this.scValue * 60000):
                this.eleEndValue = this.datePipe.transform(new Date(), 'yyyy-MM-dd HH:mm:ss');
                break;
            default:
                this.eleEndValue = this.datePipe.transform(new Date(stime).getTime() + (this.scValue * 60000 / 2), 'yyyy-MM-dd HH:mm:ss');
                break;
        }
    }
    battleSearch() {
        const beginDate = this.datePipe.transform(new Date(this.battleTimeValue).getTime() - 1 * this.beforeValue * 60 * 1000, 'yyyy-MM-dd HH:mm:ss');
        const endDate = this.datePipe.transform(new Date(this.battleTimeValue).getTime() + 1 * this.afterValue * 60 * 1000, 'yyyy-MM-dd HH:mm:ss');
        this.zctiframe = this.sanitizer.bypassSecurityTrustHtml(
            `<iframe src="/csmis/staht/HTtest.jsp?` +
            `setZoom=1.5&staId=${this.battleStationId}&beginDate=${beginDate}&endDate=${endDate}"` +
            `frameborder="0" style="width:1856px;height:420px;position:absolute;z-index:9">
            </iframe>`
        );
    }
    healthSearch() {
        this.echarts();
    }
    // 启动应急
    alarmDesc() {
        // 转设备类型和设备名称
        this.controlApiService.getDevname(this.queryParams.STATIONID, this.queryParams.DEVTYPEID, '', this.queryParams.DEVTYPE, this.queryParams.DEVNAME, '2', (devname) => {
            if (devname != '[]') {
                devname = JSON.parse(devname);
                this.router.navigate(['control/command'], {
                    queryParams: {
                        'NID': this.queryParams.NID,
                        'STATIONID': devname[0].A_STAID,
                        'STATIONNAME': encodeURI(encodeURI(devname[0].A_STANAME)),
                        'TIME': this.sjValue,
                        'ALARMTYPE': this.queryParams.ALARMTYPE,
                        'ALARMTEXT': encodeURI(encodeURI(this.queryParams.ALARMTEXT)),
                        'DEVNAMEID': devname[0].A_DEVID,
                        'DEVNAME': encodeURI(encodeURI(devname[0].A_DEVNAME)).replace(/\#/g, '%23'),
                        'DEVTYPE': devname[0].A_DEVTYPENAME,
                        'DEVTYPEID': devname[0].A_DEVTYPEID,
                        'SCVALUE': this.scValue,
                        'ALARMDESCRIPTION': ''
                    }
                });
            } else {
                this.msg.error('未找到该监测设备关联的调度中心系统设备，请检查是否成功配置！', { nzDuration: 2000 });
            }
        });
    }
    echarts() {
        const startTime = this.datePipe.transform(this.devStartValue, 'yyyy-MM-dd HH:mm:ss');
        const endTime = this.datePipe.transform(this.devEndValue, 'yyyy-MM-dd HH:mm:ss');

        this.alarmDev(this.queryParams.STATIONID, this.queryParams.DEVTYPEID, this.queryParams.DEVNAME, this.datePipe.transform(startTime, 'yyyy-MM-dd HH:mm:ss'), endTime).subscribe((res: any) => {
            if (res.msg === 'Ok') {
                if (res.data[0].length) {
                    this.echartsSeries(res, 'echart1', 'NAME', '按报警原因统计');
                }
            }
        });
        this.alarmTime(this.queryParams.STATIONID, this.queryParams.DEVTYPEID, this.queryParams.DEVNAME, startTime, endTime).subscribe((res: any) => {
            if (res.msg === 'Ok') {
                if (res.data[0].length) {
                    this.echartsSeries(res, 'echart2', 'UTIME', '按报警时间统计');
                }
            }
        })
    }


    // 智能预警报警时间
    alarmTime(stationid, devtypeid, devname, begintime, endtime) {
        let url = environment.project + '/alarmTab2/alarmTime?begintime=' + begintime + '&endtime=' + endtime;
        stationid ? url += '&stationid=' + stationid : url += '&stationid=';
        devtypeid ? url += '&devtypeid=' + devtypeid : url += '&devtypeid=';
        devname ? url += '&devname=' + encodeURI(encodeURI(devname)) : url += '&devname=';
        return this.http.get(url);
    }
    // 智能预警报警设备
    alarmDev(stationid, devtypeid, devname, begintime, endtime) {
        let url = environment.project + '/alarmTab2/alarmDev?begintime=' + begintime + '&endtime=' + endtime;
        stationid ? url += '&stationid=' + stationid : url += '&stationid=';
        devtypeid ? url += '&devtypeid=' + devtypeid : url += '&devtypeid=';
        devname ? url += '&devname=' + encodeURI(encodeURI(devname)) : url += '&devname=';
        return this.http.get(url);
    }
    echartsSeries(res, id, type, title) {
        const gettype = ['报警', '预警'];
        const getname = [];
        const getyj = [];
        const getbj = [];
        const getdata = [];
        let xname = '';

        for (const item of res.data[0]) {
            getbj.push(item[gettype[0]]);
            getyj.push(item[gettype[1]]);
            switch (type) {
                case 'NAME':
                    getname.push(item.NAME);
                    xname = '（报警原因）';
                    break;
                case 'UTIME':
                    getname.push(item.UTIME.split('-')[1] + '-' + item.UTIME.split('-')[2]);
                    xname = '（报警时间）';
                    break;
            }
        }
        getdata.push({
            name: gettype[0], type: 'bar', stack: 'two', barWidth: 20, data: getyj
        });
        getdata.push({
            name: gettype[1], type: 'bar', stack: 'two', barWidth: 20, data: getbj
        });

        echarts.init(document.getElementById(id)).setOption({
            title: {
                text: title,
                left: 'center'
            },
            legend: {
                data: gettype,
                top: 30
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: '#666'
                    }
                }
            },
            xAxis: [{
                data: getname,
                splitLine: {
                    // show: false
                },
                name: xname
                // show: false
            }],
            yAxis: [
                {
                    type: 'value',
                    name: '（数量）'
                }
            ],
            grid: {
                left: 100,
                right: 100,
                top: 60,
                bottom: 20
            },
            series: getdata
        }, true);
    }
    eleSearch() {
        // 电气特性时间
        this.tqtxTime('', this.queryParams);
        this.electricalnml = false;
        setTimeout(() => {
            this.electricalnml = true;
        }, 500);
    }
    themeChenge(e) {
        this.themeClass = e;
    }
    czjyClick(e) {
        switch (e.type) {
            case '1':
                const pc = e.param;
                const param = {
                    stationid: this.queryParams.STATIONID,
                    stationname: this.queryParams.STATIONNAME,
                    problemtype: '',
                    problemlevel: this.queryParams.ALARMLEVEL,
                    problem: this.queryParams.ALARMTEXT + ` (问题设备：${this.queryParams.DEVNAME})`,
                    pc,
                    id: this.queryParams.NID
                };
                this.jzjcMainService.addInPblmBase(param).subscribe(res => {
                    if (res.msg === 'Ok') {
                        this.msg.success('操作成功')
                    } else {
                        this.msg.error(res.msg)
                    }
                });
                break;
            default:
                break;
        }
    }
}
